package com.kaifamiao.interceptor;

import com.kaifamiao.service.TokenService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        log.info( handler.toString() );
        String auth = req.getHeader( "Authorization" );
        // 判断 auth 是否为 null 或 为空串
        if( auth == null || auth.trim().isEmpty() ) {
            return false;
        }
        log.trace( "Authorization: " + auth );
        String token = auth.substring( "Bearer ".length() );
        token = token.trim();
        log.trace( "JSON Web Token: " + token );
        // 判断 token 是否通过校验
        if( !tokenService.verify(token) ) {
            return false;
        }
        // 获取 payload 中的内容
        Map<String,Object> map = tokenService.toMap(token);
        log.trace( "payload: " + map.toString() );
        // 将当前已登录用户的 id 设置到 当前请求的属性中
        req.setAttribute( "userId", map.get( "id" ) );
        return true;
    }

}
